package com.kaizeli.website.service.impl;

import com.kaizeli.website.mapper.ContractPersonnelMapper;
import com.kaizeli.website.mapper.ProjectBasicInfoMapper;
import com.kaizeli.website.pojo.entity.ContractPersonnelDO;
import com.kaizeli.website.pojo.entity.ProjectBasicInfoDO;
import com.kaizeli.website.pojo.vo.ProjectMemberCardVO;
import com.kaizeli.website.service.ProjectMemberCardService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 项目成员卡片服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ProjectMemberCardServiceImpl implements ProjectMemberCardService {
    
    private final ProjectBasicInfoMapper projectBasicInfoMapper;
    private final ContractPersonnelMapper contractPersonnelMapper;
    
    @Override
    public List<ProjectMemberCardVO> getProjectMemberCards() {
        log.info("获取项目成员卡片列表");
        
        // 1. 获取所有项目基础信息
        List<ProjectBasicInfoDO> projects = projectBasicInfoMapper.selectList(null);
        
        // 2. 按项目编号分组
        Map<String, List<ProjectBasicInfoDO>> projectGroups = projects.stream()
                .collect(Collectors.groupingBy(ProjectBasicInfoDO::getProjectCode));
        
        // 3. 为每个项目编号组创建项目成员卡片
        return projectGroups.entrySet().stream()
                .map(entry -> createProjectMemberCard(entry.getKey(), entry.getValue()))
                .collect(Collectors.toList());
    }
    
    @Override
    public List<ProjectMemberCardVO> getProjectMemberCardsByStatus(boolean hasInactiveMembers) {
        log.info("根据状态获取项目成员卡片列表，是否有已退出成员：{}", hasInactiveMembers);
        
        // 1. 获取所有项目成员卡片
        List<ProjectMemberCardVO> cards = getProjectMemberCards();
        
        // 2. 根据是否有已退出成员进行过滤
        return cards.stream()
                .filter(card -> hasInactiveMembers ? card.getInactiveMembers() > 0 : card.getInactiveMembers() == 0)
                .collect(Collectors.toList());
    }
    
    @Override
    public List<ProjectMemberCardVO> getProjectMemberCardsByCustomer(Long customerId) {
        log.info("根据客户ID获取项目成员卡片列表，客户ID：{}", customerId);
        
        // 1. 获取指定客户的项目基础信息
        List<ProjectBasicInfoDO> projects = projectBasicInfoMapper.selectList(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<ProjectBasicInfoDO>()
                        .eq("customer_id", customerId)
        );
        
        // 2. 按项目编号分组
        Map<String, List<ProjectBasicInfoDO>> projectGroups = projects.stream()
                .collect(Collectors.groupingBy(ProjectBasicInfoDO::getProjectCode));
        
        // 3. 为每个项目编号组创建项目成员卡片
        return projectGroups.entrySet().stream()
                .map(entry -> createProjectMemberCard(entry.getKey(), entry.getValue()))
                .collect(Collectors.toList());
    }
    
    @Override
    public List<ProjectMemberCardVO> getProjectMemberCardsByContractCompany(Integer contractCompanyId) {
        log.info("根据签约公司ID获取项目成员卡片列表，签约公司ID：{}", contractCompanyId);
        
        // 1. 获取指定签约公司的项目基础信息
        List<ProjectBasicInfoDO> projects = projectBasicInfoMapper.selectList(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<ProjectBasicInfoDO>()
                        .eq("contract_company_id", contractCompanyId)
        );
        
        // 2. 按项目编号分组
        Map<String, List<ProjectBasicInfoDO>> projectGroups = projects.stream()
                .collect(Collectors.groupingBy(ProjectBasicInfoDO::getProjectCode));
        
        // 3. 为每个项目编号组创建项目成员卡片
        return projectGroups.entrySet().stream()
                .map(entry -> createProjectMemberCard(entry.getKey(), entry.getValue()))
                .collect(Collectors.toList());
    }
    
    /**
     * 创建项目成员卡片
     * 
     * @param projectCode 项目编号
     * @param projects 同一项目编号下的所有项目
     * @return 项目成员卡片
     */
    private ProjectMemberCardVO createProjectMemberCard(String projectCode, List<ProjectBasicInfoDO> projects) {
        if (projects.isEmpty()) {
            return null;
        }
        
        // 使用第一个项目作为基础信息（同一项目编号的项目基本信息应该相同）
        ProjectBasicInfoDO baseProject = projects.get(0);
        
        // 统计合同人员信息
        Map<String, Integer> memberStats = getMemberStatsByProjectCode(projectCode);
        
        // 创建项目成员卡片
        ProjectMemberCardVO card = new ProjectMemberCardVO();
        card.setProjectCode(projectCode);
        card.setProjectName(baseProject.getProjectName());
        card.setTotalMembers(memberStats.get("total"));
        card.setActiveMembers(memberStats.get("active"));
        card.setInactiveMembers(memberStats.get("inactive"));
        card.setStartDate(baseProject.getStartDate());
        card.setEndDate(baseProject.getEndDate());
        card.setProjectType(baseProject.getProjectType());
        card.setProjectTypeName(getProjectTypeName(baseProject.getProjectType()));
        card.setManagerId(baseProject.getManagerId());
        card.setCustomerId(baseProject.getCustomerId());
        card.setContractCompanyId(baseProject.getContractCompanyId());
        
        return card;
    }
    
    /**
     * 根据项目编号统计合同人员信息
     * 
     * @param projectCode 项目编号
     * @return 统计信息Map
     */
    private Map<String, Integer> getMemberStatsByProjectCode(String projectCode) {
        // 查询该项目编号下的所有合同人员
        List<ContractPersonnelDO> personnelList = contractPersonnelMapper.selectList(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<ContractPersonnelDO>()
                        .eq("project_code", projectCode)
        );
        
        int total = personnelList.size();
        // 获取当前日期
        java.time.LocalDate now = java.time.LocalDate.now();
        
        // 统计正常成员：优先检查 status 字段，如果 status 为空或不是 active，再根据 endDate 判断
        int active = 0;
        int inactive = 0;
        
        for (ContractPersonnelDO personnel : personnelList) {
            // 优先使用 status 字段判断
            if ("active".equalsIgnoreCase(personnel.getStatus())) {
                // status 为 active，认为是正常状态
                active++;
            } else if (personnel.getStatus() != null && !personnel.getStatus().isEmpty()) {
                // status 不为空且不是 active，认为已退出
                inactive++;
            } else {
                // status 为空，根据 endDate 判断
                if (personnel.getEndDate() == null) {
                    // 没有结束日期，认为是正常状态
                    active++;
                } else if (!personnel.getEndDate().isBefore(now)) {
                    // 结束日期等于今天或未来，认为是正常状态
                    active++;
                } else {
                    // 结束日期是过去日期，认为已退出
                    inactive++;
                }
            }
        }
        
        Map<String, Integer> stats = new java.util.HashMap<>();
        stats.put("total", total);
        stats.put("active", active);
        stats.put("inactive", inactive);
        
        log.debug("项目编号: {}, 总人数: {}, 正常: {}, 已退出: {}", projectCode, total, active, inactive);
        
        return stats;
    }
    
    /**
     * 根据项目类型字符串获取类型名称
     */
    private String getProjectTypeName(String projectType) {
        if (projectType == null || projectType.isEmpty()) {
            return null;
        }
        
        switch (projectType.toLowerCase()) {
            case "manpower":
            case "1":
                return "人力项目";
            case "turnkey":
            case "2":
                return "整包项目";
            case "subcontract":
            case "3":
                return "分包项目";
            default:
                return projectType; // 如果不知道的类型，直接返回原值
        }
    }
}
